/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.baidu.elinkagescroll;

import com.baidu.elinkagescroll.utils.LogUtil;

import com.ryan.ohos.extension.scroller.Scroller;

import ohos.agp.components.Component;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * description :
 *
 * @since 2021/7/16
 */
class SmoothScrollRunnable implements Runnable {
    private EventHandler mHandler;
    /**
     * Scrollable view
     */
    private final Component mView;
    /**
     * Need to calculate offset.
     */
    private final Scroller mScroller;

    private int mLastX;
    private int mLastY;

    SmoothScrollRunnable(Component view) {
        mView = view;
        mHandler = new EventHandler(EventRunner.getMainEventRunner());
        mScroller = new Scroller(view.getContext());
    }

    void start(int initX, int initY, int initialVelocityX, int initialVelocityY, int maxX, int maxY) {
        // start smooth scrolling
        mScroller.fling(initX, initY, initialVelocityX, initialVelocityY, Integer.MIN_VALUE, maxX, Integer.MIN_VALUE, maxY);
        // save new data
        mLastX = initX;
        mLastY = initY;

        // run self
        mHandler.postTask(this, 5);
    }

    void start(int startX, int startY, int dx, int dy) {
        mScroller.startScroll(startX, startY, dx, dy);
        // save new data
        mLastX = startX;
        mLastY = startY;
        mHandler.postTask(this, 5);
    }

    void removeTask() {
        mHandler.removeTask(this);
    }

    @Override
    public void run() {
        if (mScroller.isFinished()) {
            return;
        }
        LogUtil.loge("parentFling velocityY = " + " " + mScroller.getFinalY());
        // calculate offset
        boolean more = mScroller.computeScrollOffset();
        int currX = mScroller.getCurrX();
        int currY = mScroller.getCurrY();
        int diffX = mLastX - currX;
        int diffY = mLastY - currY;
        if (diffX != 0 || diffY != 0) {
            mView.scrollBy(diffX, diffY);
            mLastX = currX;
            mLastY = currY;
        }

        if (more) {
            // run self
            mHandler.postTask(this, 5);
        }
    }

    boolean isFinished() {
        return mScroller.isFinished();
    }

    void forceFinished() {
        if (!mScroller.isFinished()) {
            mScroller.forceFinished(true);
        }
    }
}